package com.xiaode.controller.admin.authority;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.*;
import com.xiaode.common.model.base.BaseAdmin;
import com.xiaode.exce.EnumError;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

public class AuthorityService {

    /**
     * 角色列表
     * @param name
     * @param state
     * @return
     * @throws Exception
     */
    public Ret list(String name, String state) throws Exception {
        Kv kv = Kv.by("name", name).set("state", state);
        List<Role> roleList = Role.dao.template("roleList", kv).find();
        return Ret.ok("roleList", roleList);
    }

    /**
     * 创建角色
     * @param name 角色名称
     * @param desc 角色描述
     * @return
     * @throws Exception
     */
    public Ret create(String name, String desc) throws Exception {
        Role role = new Role();
        role.setName(name);
        role.setDesc(desc);
        role.setAddTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        role.setState(1);
        role.save();
        return Ret.ok("roleList", roleOptions());
    }

    /**
     * 删除角色
     * @param roleId  角色id
     * @return
     * @throws Exception
     */
    @Before(Tx.class)
    public Ret delete(Integer roleId) throws Exception {
        // 是否存在关联此角色的管理员
        List<String> roleIdsList = Db.query("SELECT roleIds FROM admin");
        for (String roleIds : roleIdsList) {
            List<Integer> roleIdlList = JSONUtil.toList(roleIds, Integer.class);
            boolean b = CollectionUtil.contains(roleIdlList, roleId);
            if (b) {
                return Ret.fail().set("error", EnumError.HAVE_RELATION_ADMIN.getObj());
            }
        }
        //删除
        Role.dao.deleteById(roleId);
        //删除权限
        Db.delete("DELETE FROM role_permission WHERE roleId = ?", roleId);

        return Ret.ok("roleList", roleOptions());
    }

    /**
     * 编辑角色
     * @param id  角色id
     * @param name  角色名称
     * @param desc  角色描述
     * @param state 启用/禁用
     * @param readOnly
     * @return
     * @throws Exception
     */
    public Ret update(Integer id, String name, String desc, Integer state, Integer readOnly) throws Exception {
        Role role = Role.dao.findById(id);
        if (BeanUtil.isEmpty(role)) {
            return Ret.fail().set("error", EnumError.ROLE_NULL.getObj());
        }
        if (name != null) {
            if (id == 2) {
                return Ret.fail().set("error", EnumError.TEACHER_ROLE_NOT_ALLOW_UPDATE.getObj());
            }
            role.setName(name);
        }
        role.setDesc(desc);
        role.setUpdateTime(LocalDateTime.now());
        if (state != null) {
            if (id == 2) {
                return Ret.fail().set("error", EnumError.TEACHER_ROLE_NOT_ALLOW_UPDATE.getObj());
            }
            role.setState(state);
        }
        if (readOnly != null) {
            role.setReadOnly(readOnly);
        }
        role.update();

        return Ret.ok("roleList", roleOptions());
    }

    /**
     * 角色批量授权
     * @param trueList  要添加的权限
     * @param falseList  需要删除的权限
     * @param authorityId 角色id
     * @return
     * @throws Exception
     */
    @Before(Tx.class)
    public Ret setPermission(String trueList, String falseList, Integer authorityId) throws Exception {
        Authority authority = Authority.dao.findById(authorityId);
        String permissionName = authority.getName();
        LocalDateTime now = LocalDateTime.now();
        List<Integer> roleIdList = JSONUtil.toList(trueList, Integer.class);
        List<Integer> deleteList = JSONUtil.toList(falseList, Integer.class);
        List<RolePermission> list = CollectionUtil.newArrayList();
        //新增权限
        Map<String, Map<Integer, List<String>>> readEditPermissionMap = Redis.use().get("readEditPermissionMap");
        Map<Integer, List<String>> listMap = readEditPermissionMap.get(permissionName);
        List<String> permissionList = listMap.get(1);
        ArrayList<String> editList = new ArrayList<>();
        editList.addAll(permissionList);
        editList.addAll(listMap.get(2));


        //添加权限
        for (Integer roleId : roleIdList) {
            Role role = Role.dao.findById(roleId);
            if (BeanUtil.isEmpty(role)) {
                return Ret.fail().set("error", EnumError.ROLE_NULL.getObj());
            }
            RolePermission rolePermission = new RolePermission();
            rolePermission.setAuthorityId(authorityId);
            rolePermission.setReadOnly(role.getReadOnly());
            rolePermission.setRoleId(roleId);
            rolePermission.setAddTime(now);
            rolePermission.setUpdateTime(now);
            list.add(rolePermission);
        }

        //删除权限
        if (deleteList.size() > 0) {
            Kv kv = Kv.by("idList", deleteList).set("authorityId",authorityId);
            Db.template("deletePermission", kv).delete();
        }
        if (list.size() > 0) {
            Db.batchSave(list, list.size());
        }
        return Ret.ok();
    }

    /**
     * 权限列表
     * @param roleId
     * @param permPointTree
     * @param allPermPoint
     * @return
     * @throws Exception
     */
    public Ret permissionList(Integer roleId, List<Kv> permPointTree, Set<String> allPermPoint) throws Exception {
        Role role = Role.dao.findById(roleId);
        if (BeanUtil.isEmpty(role)) {
            return Ret.fail().set("error", EnumError.ROLE_NULL.getObj());
        }
        // 角色拥有的权限
        List<String> permissionList = Db.query("SELECT ap.permission FROM role_permission rp INNER JOIN authority_permission ap ON rp.authorityId = ap.authorityId WHERE roleId = ?", roleId);
//        List<String> permissionList = Db.query("SELECT permission FROM role_permission WHERE roleId = ? ", roleId);
        Set<String> permissionPoint = new HashSet<String>();
        for (String permission : permissionList) {
            permissionPoint.add(permission);
        }
        return Ret.ok("systemPermissions", permPointTree).set("assignedPermissions", permissionPoint).set("allPermPoint", allPermPoint);
    }


    /**
     * 给教师赋角色
     *
     * @param
     * @return
     */
    @Before(Tx.class)
    public Ret roleToTeacher(String trueListStr, String falseListStr, Integer roleId) throws Exception {
        Cache redis = Redis.use();
        List<Integer> roleInsertList = JSONUtil.toList(trueListStr, Integer.class);
        List<Integer> roleDeleteList = JSONUtil.toList(falseListStr, Integer.class);
        ArrayList<Admin> admins = new ArrayList<>(roleDeleteList.size() + roleInsertList.size());
        Kv kv = Kv.create();
        if (roleInsertList != null && roleInsertList.size() > 0) {
            kv.set("roleList", roleInsertList);
            List<Admin> insertAdminByIdList = Admin.dao.template("findAdminByIdList", kv).find();
            List<Integer> collect = insertAdminByIdList.stream().map(Admin::getId).collect(Collectors.toList());
            insertAdminByIdList = Admin.dao.template("findAdminByAccountList", Kv.by("accountList", collect)).find();
            for (int i = 0; i < insertAdminByIdList.size(); i++) {
                //给教师添加角色
                Admin admin = insertAdminByIdList.get(i);
                String roleIds = admin.getRoleIds();
                List<Integer> roleIdList = JSONUtil.toList(roleIds, Integer.class);
                roleIdList.add(roleId);
                //去重
                ArrayList<Integer> list = new ArrayList<>(new HashSet<>(roleIdList));
                String s = JSONUtil.toJsonStr(list);
                admin.setRoleIds(s);
                admins.add(admin);
                //更新redis
                Admin o = redis.get(Const.user.Admin + admin.getId());
                o.setRoleIds(s);
                redis.set(Const.user.Admin + admin.getId(),o);
            }
        }
        if (roleDeleteList != null && roleDeleteList.size() > 0) {
            kv.set("roleList", roleDeleteList);
            List<Admin> deleteAdminByIdList = Admin.dao.template("findAdminByIdList", kv).find();
            List<Integer> collect = deleteAdminByIdList.stream().map(Admin::getId).collect(Collectors.toList());
            deleteAdminByIdList = Admin.dao.template("findAdminByAccountList", Kv.by("accountList", collect)).find();
            for (int i = 0; i < deleteAdminByIdList.size(); i++) {
                //给教师添加角色
                Admin admin = deleteAdminByIdList.get(i);
                String roleIds = admin.getRoleIds();
                List<Integer> roleIdList = JSONUtil.toList(roleIds, Integer.class);
                roleIdList.remove(roleId);
                //去重
                String s = JSONUtil.toJsonStr(roleIdList);
                admin.setRoleIds(s);
                admins.add(admin);
                //更新redis
                Admin o = redis.get(Const.user.Admin + admin.getId());
                o.setRoleIds(s);
                redis.set(Const.user.Admin + admin.getId(),o);
            }
        }
        //批量保存
        Db.batchUpdate(admins, admins.size());
        return Ret.ok();
    }


    /**
     * 角色成员
     *
     * @param roleId
     * @return
     */
    public Ret roleMemberIds(Integer roleId) throws Exception {
        List<Admin> admins = Admin.dao.find("SELECT id,roleIds,user_type FROM admin WHERE isDele = 0");
        List<Integer> collect = admins.stream().filter(admin -> {
            if(admin.getUserType() == 0){
                return false;
            }
            String roleIds = admin.getRoleIds();
            List<Integer> integers = JSONUtil.toList(roleIds, Integer.class);
            return integers.contains(roleId);
        }).map(BaseAdmin::getId).collect(Collectors.toList());
        return Ret.ok("admins", collect);
    }


    /**
     * 查询权限分类
     *
     * @return
     */
    public Ret findAuthority() throws Exception {
        List<Authority> all = Authority.dao.findAll();
        return Ret.ok("authority", all);
    }

    /**
     * 角色授权
     *
     * @param roleId
     * @return
     */
    @Before(Tx.class)
    public Ret setRolePermission(Integer roleId, String permissionIds, Integer readOnly) throws Exception {
        List<Integer> permissionList = JSONUtil.toList(permissionIds, Integer.class);
//        Map<String, Map<Integer, List<String>>> readEditPermissionMap = Redis.use().get("readEditPermissionMap");
        //查询角色
        Role role = Role.dao.findById(roleId);
        if (BeanUtil.isEmpty(role)) {
            return Ret.fail().set("error", EnumError.ROLE_NULL.getObj());
        }
        if (!role.getReadOnly().equals(readOnly)) {
            role.setReadOnly(readOnly);
            role.update();
        }
        ArrayList<RolePermission> rolePermissions = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (Integer integer : permissionList) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setAuthorityId(integer);
            rolePermission.setReadOnly(role.getReadOnly());
            rolePermission.setAddTime(now);
            rolePermission.setUpdateTime(now);
            rolePermissions.add(rolePermission);
        }
        //  删除原有权限
        Db.update("DELETE FROM role_permission WHERE roleId = ?", roleId);
        Db.batchSave(rolePermissions,rolePermissions.size());
        //保存所有要存储的权限
//        ArrayList<String> myPermissionList = new ArrayList<>();
//        for (Integer s : permissionList) {
//            Authority authority = Authority.dao.findById(s);
//            Map<Integer, List<String>> listMap = readEditPermissionMap.get(authority.getName());
//            myPermissionList.addAll(listMap.get(1));
        //如果角色拥有编辑权限
//            if (readOnly == 2) {
//                myPermissionList.addAll(listMap.get(2));
//            }
//        }
//        List<RolePermission> rolePermissionList = new ArrayList<>();
//        for (int i = 0; i < myPermissionList.size(); i++) {
//            String s = myPermissionList.get(i);
//            RolePermission rolePermission = new RolePermission();
//            rolePermission.setPermission(s);
//            rolePermission.setRoleId(roleId);
//            rolePermissionList.add(rolePermission);
//        }
//        Db.batchSave(rolePermissionList, rolePermissionList.size());

        return Ret.ok();
    }

    /**
     * 根据角色查询拥有的权限
     *
     * @param roleId
     * @return
     */
    public Ret findRolePermission(Integer roleId) throws Exception {
        //如果拥有最大权限
//        RolePermission rolePermission = RolePermission.dao.findFirst("SELECT * FROM role_permission WHERE roleId = ? AND permission = '*'", roleId);
//        if (rolePermission != null) {
//            List<AuthorityPermission> authorityPermissions = AuthorityPermission.dao.find("SELECT id from authority");
//            List<Integer> collect = authorityPermissions.stream().map(authorityPermission -> authorityPermission.getId()).collect(Collectors.toList());
//            return Ret.ok("permissionList", collect);
//        }
        List<Record> records = Db.template("findRolePermission", Kv.by("roleId", roleId)).find();
        List<Integer> idList = records.stream().map(record -> record.getInt("id")).collect(Collectors.toList());
        return Ret.ok("permissionList", idList);
    }

    /**
     * 查询拥有该权限的角色
     *
     * @param authorityId
     * @return
     */
    public Ret findPermissionRole(Integer authorityId) throws Exception {
        //查询拥有所有权限的角色
//        List<RolePermission> rolePermissionList = RolePermission.dao.find("SELECT roleId FROM role_permission WHERE permission = '*'");
//        Set<Integer> collect = rolePermissionList.stream().map(rolePermission -> rolePermission.getInt("roleId")).collect(Collectors.toSet());
        List<Record> records = Db.template("findPermissionRole", Kv.by("authorityId", authorityId)).find();
        Set<Integer> roleId = records.stream().map(record -> record.getInt("roleId")).collect(Collectors.toSet());
//        roleId.addAll(collect);
        return Ret.ok("roleList", roleId);
    }

    /**
     * 编辑权限
     *
     * @param authorityId
     * @param describe
     * @return
     */
    public Ret editAuthority(Integer authorityId, String describe) throws Exception {
        Authority authority = Authority.dao.findById(authorityId);
        if (authority == null) {
            return Ret.fail().set("error", EnumError.AUTHORITY_NOT_EXIT.getObj());
        }
        authority.setDescribe(describe);
        authority.update();
        return Ret.ok();
    }

    /**
     * 添加节点
     *
     * @param stratum      节点层级 1.根节点  2.年级  3.班级
     * @param name         节点名称
     * @param parentNodeId 父节点Id
     * @return
     */
    public Ret addNode(Integer stratum, String name, Integer parentNodeId) throws Exception {
        if (stratum == 1) {
            OrgGrade orgGrade = OrgGrade.dao.findFirst("SELECT id FROM org_grade WHERE isRoot = 1");
            if (orgGrade != null) {
                return Ret.fail().set("error", EnumError.ROOT_NODE_EXIT.getObj());
            }
            OrgGrade grade = new OrgGrade();
            grade.setIsRoot(true);
            grade.setName(name);
            grade.save();
        } else if (stratum == 2) {
            OrgGrade grade = OrgGrade.dao.findFirst("SELECT id FROM org_grade WHERE name = ?", name);
            if (grade != null) {
                return Ret.fail().set("error", EnumError.NODE_NAME_REPEAT.getObj());
            }
            OrgGrade orgGrade = new OrgGrade();
            orgGrade.setIsRoot(false);
            orgGrade.setName(name);
            orgGrade.save();
        } else {
            OrgClass first = OrgClass.dao.findFirst("SELECT id FROM org_class WHERE adminGradeId = ? AND name = ?", parentNodeId, name);
            if (first != null) {
                return Ret.fail().set("error", EnumError.NODE_NAME_REPEAT.getObj());
            }
            OrgClass orgClass = new OrgClass();
            orgClass.setAdminGradeId(parentNodeId);
            orgClass.setName(name);
            orgClass.setState(1);
            orgClass.save();
        }
        return Ret.ok("gradeClassInfo", findGradeClassInfo());
    }

    /**
     * 删除节点
     *
     * @param stratum 节点层级
     * @param nodeId  节点Id
     * @return
     */
    @Before(Tx.class)
    public Ret delNode(Integer stratum, Integer nodeId) throws Exception {
        Kv kv = Kv.by("nodeId", nodeId);
        //删除根节点 就是删除所有节点
        if (stratum == 1) {
            return Ret.fail().set("error", EnumError.ROOT_NODE_NOT_ALLOW_DELETE.getObj());
        } else if (stratum == 2) {
            //判断当前节点下有没有学生
            kv.setIfNotNull("gradeId",nodeId);
            List<Record> records = Db.template("findStudentUnderGradeNode", kv).find();
            if (records != null && records.size() > 0) {
                return Ret.fail().set("error", EnumError.NODE_EXIT_STUDENT.getObj());
            }
            Db.delete("DELETE FROM org_grade WHERE id = ?", nodeId);
            List<OrgClass> orgClasses = OrgClass.dao.find("SELECT id FROM org_class WHERE adminGradeId = ?", nodeId);
            List<Integer> collect = orgClasses.stream().map(orgClass -> orgClass.getId()).collect(Collectors.toList());
            Kv idList = Kv.by("idList", collect);
            if (ObjectUtil.isAllNotEmpty(collect)){
                Db.template("deleteOrgAdminByIdList", idList).delete();
            }
            Db.delete("DELETE FROM org_class WHERE adminGradeId = ?", nodeId);
            //删除绑定的教师
            Db.delete("DELETE FROM org_admin WHERE stratum = 2 AND stratumId = ?", nodeId);
        } else {
            List<Record> records = Db.template("findStudentUnderClassNode", kv).find();
            if (records != null && records.size() > 0) {
                return Ret.fail().set("error", EnumError.NODE_EXIT_STUDENT.getObj());
            }
            //删除节点及教师绑定关系
            Db.delete("DELETE FROM org_class WHERE id = ?", nodeId);
            Db.delete("DELETE FROM org_admin WHERE stratum = 3 AND stratumId = ?", nodeId);
            //删除数据权限
            Db.delete("DELETE FROM data_permission WHERE clasId = ? ",nodeId);
        }

        return Ret.ok("gradeClassInfo", findGradeClassInfo());
    }

    /**
     * 编辑节点
     *
     * @param stratum 层级
     * @param nodeId  节点id
     * @param name    描述
     * @return
     */
    public Ret updateNode(Integer stratum, Integer nodeId, String name) {
        if (stratum == 1 || stratum == 2) {
            //查询节点
            OrgGrade orgGrade = OrgGrade.dao.findById(nodeId);
            if (orgGrade == null) {
                return Ret.fail().set("error", EnumError.NODE_NOT_EXIT.getObj());
            }
            OrgGrade first = OrgGrade.dao.findFirst("SELECT id FROM org_grade WHERE name = ?", name);
            if (first != null) {
                return Ret.fail().set("error", EnumError.NODE_NAME_REPEAT.getObj());
            }
            orgGrade.setName(name);
            orgGrade.update();
        } else {
            OrgClass orgClass = OrgClass.dao.findById(nodeId);
            if (orgClass == null) {
                return Ret.fail().set("error", EnumError.NODE_NOT_EXIT.getObj());
            }
            OrgClass first = OrgClass.dao.findFirst("SELECT id FROM org_class WHERE adminGradeId = ? AND name = ?", orgClass.getAdminGradeId(), name);
            if (first != null) {
                return Ret.fail().set("error", EnumError.NODE_NAME_REPEAT.getObj());
            }
            orgClass.setName(name);
            orgClass.update();
        }
        return Ret.ok("gradeClassInfo", findGradeClassInfo());
    }

    /**
     * 查询架构
     *
     * @return
     */
    public Ret findNode() throws Exception {
        //查询根节点
        Cache redis = Redis.use();
        OrgGrade rootNode = OrgGrade.dao.findFirst("SELECT * FROM org_grade WHERE isRoot = 1");
        if (rootNode == null) {
            return Ret.ok("rootNode", rootNode);
        }
        rootNode.put("type", 1);
        List<OrgAdmin> orgAdmins = OrgAdmin.dao.find("SELECT adminId FROM org_admin WHERE stratum = 1");
        List<Integer> adminIdList = orgAdmins.stream().map(orgAdmin -> orgAdmin.getAdminId()).filter(integer ->
        {
            Admin admin = redis.get(Const.user.Admin + integer);
            return admin.getUserType() == 1;
        }).collect(Collectors.toList());
        rootNode.put("admins", adminIdList);
        rootNode.put("tableId", "1:" + rootNode.getId());
        //查询年级
        List<OrgGrade> orgGrades = OrgGrade.dao.find("SELECT id,name FROM org_grade WHERE isRoot = 0");
        for (OrgGrade orgGrade : orgGrades) {
            orgGrade.put("type", 2);
            List<OrgAdmin> orgGradeAdmins = OrgAdmin.dao.find("SELECT adminId FROM org_admin WHERE stratum = 2 AND stratumId = ?", orgGrade.getId());
            List<Integer> adminId = orgGradeAdmins.stream().map(orgAdmin -> orgAdmin.getAdminId()).filter(integer ->
            {
                Admin admin = redis.get(Const.user.Admin + integer);
                if (admin == null){
                    return false;
                }
                return admin.getUserType() == 1;
            }).collect(Collectors.toList());
            orgGrade.put("admins", adminId);
            orgGrade.put("tableId", "2:" + orgGrade.getId());
            List<OrgClass> orgClasses = OrgClass.dao.find("SELECT id,name FROM org_class WHERE adminGradeId = ?", orgGrade.getId());
            for (OrgClass orgClass : orgClasses) {
                orgClass.put("type", 3);
                List<OrgAdmin> orgClassAdmins = OrgAdmin.dao.find("SELECT adminId FROM org_admin WHERE stratum = 3 AND stratumId = ?", orgClass.getId());
                List<Integer> cadminIdList = orgClassAdmins.stream().map(orgAdmin -> orgAdmin.getAdminId()).filter(integer ->
                {
                    Admin admin = redis.get(Const.user.Admin + integer);
                    if (BeanUtil.isEmpty(admin)){
                        return false;
                    }
                    return admin.getUserType() == 1;
                }).collect(Collectors.toList());
                orgClass.put("admins", cadminIdList);
                orgClass.put("tableId", orgClass.getId());
            }
            orgGrade.put("children", orgClasses);
        }
        rootNode.put("children", orgGrades);
        return Ret.ok("rootNode", rootNode);
    }

    /**
     * 节点成员管理
     *
     * @param stratum 层级
     * @param nodeId  节点id
     * @param idList  教师id列表
     * @return
     */
    @Before(Tx.class)
    public Ret nodeMemberManage(Integer stratum, Integer nodeId, String idList) {
        Cache redis = Redis.use();
        //查询节点是否存在
        if (stratum == 1 || stratum == 2) {
            OrgGrade orgGrade = OrgGrade.dao.findFirst("SELECT id FROM org_grade WHERE isRoot = ? AND id = ?", 2 - stratum, nodeId);
            if (orgGrade == null) {
                return Ret.fail().set("error", EnumError.NODE_NOT_EXIT.getObj());
            }
        } else {
            OrgClass orgClass = OrgClass.dao.findById(nodeId);
            if (orgClass == null) {
                return Ret.fail().set("error", EnumError.NODE_NOT_EXIT.getObj());
            }
        }
        //删除原来教师
        List<Record> records = Db.find("SELECT ad.accountId FROM org_admin oa INNER JOIN admin ad ON ad.id = oa.adminId WHERE oa.stratum = ? AND oa.stratumId = ?",stratum,nodeId);
        for (Record record : records) {
            redis.del(Const.user.loginAdmin + record.getStr("accountId"));
        }
        Db.delete("DELETE FROM org_admin WHERE stratum = ? AND stratumId = ?", stratum, nodeId);
        ArrayList<OrgAdmin> orgAdmins = new ArrayList<>();
        List<Integer> idsList = JSONUtil.toList(idList, Integer.class);
//        List<String> list = idsList.stream().map(integer ->
//                {
//                    Admin o = redis.get(Const.user.Admin + integer);
//                    String account = o.getJobNum();
//                    return account;
//                }
//        ).collect(Collectors.toList());
        //查询所有账号
        if (idsList.isEmpty()){
            return Ret.ok();
        }
        idsList = Db.template("findAdminByAccountList", Kv.by("accountList", idsList)).find().stream().map(record -> record.getInt("id")).collect(Collectors.toList());
        for (Integer id : idsList) {
            OrgAdmin orgAdmin = new OrgAdmin();
            orgAdmin.setStratum(stratum);
            orgAdmin.setStratumId(nodeId);
            orgAdmin.setAdminId(id);
            orgAdmins.add(orgAdmin);
        }
        Db.batchSave(orgAdmins, orgAdmins.size());

        return Ret.ok();
    }
    
    
    
    
    
    
    
    
    public static List<Kv> roleOptions() {
    	List<Role> roleList = Role.dao.findAll();
      	List<Kv> list = new LinkedList<>();
      	roleList.forEach(item -> {
      		Kv kv = Kv.create();
      		kv.set("value", item.getId());
      		kv.set("label", item.getName());
      		list.add(kv);
      	});
      	return list;
    }
    
    public static List<OrgGrade> findGradeClassInfo() {
    	//查询学生届别班级
    	List<OrgGrade> orgGrades = OrgGrade.dao.find("SELECT id,name FROM org_grade WHERE isRoot = 0");
      	for (OrgGrade orgGrade : orgGrades) {
      		List<OrgClass> orgClasses = OrgClass.dao.find("SELECT id,name FROM org_class WHERE adminGradeId = ?", orgGrade.getId());
      		orgGrade.put("class", orgClasses);
      	}
      	return orgGrades;
    }

}
